<?php
# last modified 2016-7-7
## 参数区
# 留底目录
$backup_dir = '/tmp/mj/backup';
# colab脚本所在目录，注意不可包含空格及特殊字符
$colab_bin_dir = '/home/user/colab/bin';
# 测试集所在目录
$testset_dir = '/home/user/colab-tests';
# 调试开关
$debug = true;
# 学号与测试集的对应关系
# 注意：测试集名称不要包含[a-zA-Z0-9_-]之外的字符！
function get_problem_name($author) {
	return 'p5-1';
	if (ord(substr($author, -1)) & 1) {
		# 学号为奇数
		return 'p5-2+movn';
	}
	return 'p5-2+movz';
}
## 参数区结束
function error($msg) {
	$escaped = htmlspecialchars($msg);
	echo "<ul><li><h4>错误信息：</h4></li><pre><code>$escaped</code></pre></ul>\n";
	exit;
}
# 上传文件大小不得超过64KB
if ($_FILES['file_upload']['size'] > 0x10000) {
	error('文件过大');
}
if ($debug) {
	$author = 'admin';
} else {
	$author = $_POST['author'];
	if (preg_match('/^[0-9]{8}$/', $author)) {
		error('学号无效');
	}
}
# $problem变量保存测试项目的名称
$problem = get_problem_name($author);
if ($debug) {
	echo "<p>测试集：$problem</p>";
}
$upload_fname = $_FILES["file_upload"]["name"];
$backup_path = "$backup_dir/$author";
if (!file_exists($backup_path)) {
	if (!mkdir($backup_path, 0777, true)) {
		error("无法创建目录$backup_path");
	}
}
$timestr = time();
$target_file = "$backup_path/${timestr}_$upload_fname";
$upload_tmpfile = $_FILES["file_upload"]["tmp_name"];
if (move_uploaded_file($upload_tmpfile, $target_file)) {
	$fdspec = array(0 => array('pipe', 'r'),
			1 => array('pipe', 'w'),
			2 => array('pipe', 'w'));
	$env = array(
		'PATH' => "/usr/local/bin:/usr/bin:/bin:$colab_bin_dir"
	);
	# $author is either 'admin' or /[0-9]{8}/
	$proc = proc_open(
		"colab-wrapper -a $author judge ".escapeshellarg($target_file)." $testset_dir/$problem",
		$fdspec,
		$pipes,
		dirname(__FILE__),
		$env);
	$stdout = stream_get_contents($pipes[1]);
	fclose($pipes[1]);
	$stderr = stream_get_contents($pipes[2]);
	fclose($pipes[2]);
	if (empty($stdout)) {
		error($stderr);
	}
	echo $stdout;
} else {
	error('文件上传失败');
}
?>
